package Demo54;

/**
 * 两两交换链表中的节点
 * https://leetcode.cn/problems/swap-nodes-in-pairs/description/
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode newHead = new ListNode();
        newHead.next = head;
        ListNode prve = newHead;
        while(prve != null) {
            // 更新节点
            ListNode cur = prve.next;
            if(cur == null) {
                break;
            }
            ListNode next = cur.next;
            if(next == null) {
                break;
            }
            // 交换
            ListNode nnext = next.next;
            prve.next = next;
            next.next = cur;
            cur.next = nnext;
            // 更新节点
            prve = cur;
        }
        return newHead.next;
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = new int[] {2,1,3,4};
        ListNode head = new ListNode();
        ListNode cur = head;
        for(int a:arr) {
            cur.next = new ListNode(a);
            cur = cur.next;
        }
        ListNode ret = solution.swapPairs(head.next);
        while(ret != null) {
            System.out.print(ret.val + " ");
            ret = ret.next;
        }
    }
}